package com.examinantsdk.base;

import android.app.Activity;


import java.util.LinkedList;
import java.util.List;

import kotlin.collections.CollectionsKt;

/**
 * Create by Carson on 2021/3/16.
 * BaseAppManager
 */
public class BaseAppManager {

    private static final String TAG = BaseAppManager.class.getSimpleName();
    private static BaseAppManager manager;
    private List<Activity> mActivities;

    public List<Activity> getActivities() {
        return mActivities;
    }

    public void setActivities(List<Activity> activities) {
        mActivities = activities;
    }

    private BaseAppManager() {
        mActivities = new LinkedList<Activity>();
    }

    public static BaseAppManager getInstance() {
        if (null == manager) {
            synchronized (BaseAppManager.class) {
                if (null == manager) {
                    manager = new BaseAppManager();
                }
            }
        }
        return manager;
    }

    /**
     * 添加Activity
     *
     * @param activity
     */
    public synchronized void addActivity(Activity activity) {
        mActivities.add(activity);
    }

    public int size() {
        return mActivities.size();
    }

    /**
     * 取得栈顶Activity
     *
     * @return
     */
    public synchronized Activity getFrontActivity() {
        Activity activity = CollectionsKt.getOrNull(mActivities, size() - 1);
        return activity;
    }

    /**
     * 移除Activity
     *
     * @param activity
     */
    public synchronized void removeActivity(Activity activity) {
        if (mActivities.contains(activity)) {
            mActivities.remove(activity);
        }
    }

    /**
     * 结束所有Activity
     */
    public synchronized void clear() {
        for (int i = mActivities.size() - 1; i > -1; i--) {
            Activity activity = CollectionsKt.getOrNull(mActivities, i);
            if (activity != null){
                removeActivity(activity);
                activity.finish();
            }
        }
    }

    /**
     * 结束指定Activity
     */
    public synchronized void finishActivity(Class<?> cls) {
        for (int i = mActivities.size() - 1; i > -1; i--) {
            Activity activity = CollectionsKt.getOrNull(mActivities, i);
            if (activity != null && activity.getClass().equals(cls)){
                removeActivity(activity);
                activity.finish();
            }
        }
    }


    public Activity findActivity(Class<?> cls) {
        Activity targetActivity = null;
        if (mActivities != null) {
            for (Activity activity : mActivities) {
                if (activity.getClass().equals(cls)) {
                    targetActivity = activity;
                    break;
                }
            }
        }
        return targetActivity;
    }

}
